package org.notes.multi;

import cn.hutool.core.util.RandomUtil;
import lombok.SneakyThrows;

import java.util.concurrent.CompletableFuture;

public class TicketDemo {
//    3. 模拟售票系统：三个窗口同时销售100张票，需处理线程安全问题，避免超卖。
    public static void main(String[] args) {
        Ticket ticket = new Ticket();
//        Thread t1 = new Thread(ticket, "窗口1");
//        Thread t2 = new Thread(ticket, "窗口2");
//        Thread t3 = new Thread(ticket, "窗口3");
//        t1.start();
//        t2.start();
//        t3.start();
        CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
            new Thread(ticket, "窗口1");
        });

        CompletableFuture<Void> future1 = CompletableFuture.runAsync(() -> {
            new Thread(ticket, "窗口2");
        });

        CompletableFuture<Void> future2 = CompletableFuture.runAsync(() -> {
            new Thread(ticket, "窗口3");
        });
        future.join();
        future1.join();
        future2.join();

    }
}
class Ticket implements Runnable {
    private int ticket = 100;
    @SneakyThrows
    public void run() {
        while (ticket > 0) {
            Thread.sleep(RandomUtil.randomInt(1000, 2000));
            synchronized (this) {
                if (ticket > 0) {
                    System.out.println(Thread.currentThread().getName() + "正在出售第" + (ticket--) + "张票");
                }
            }
        }
    }
}
